//
//  DiyDrawViewController.m
//  BlueToothProject
//
//  Created by foshou on 2017/2/28.
//  Copyright © 2017年 yxw. All rights reserved.
//

#import "DiyDrawViewController.h"
#import "DiyDrawView.h"
#import "ColorPickerViewController.h"
#import "DiyHeader.h"
#import <Photos/Photos.h>
#import "BlueToothService.h"
#import "SVProgressHUD.h"
#import <AssetsLibrary/AssetsLibrary.h>
@interface DiyDrawViewController ()<DrawViewOptionDelegate>

@property (nonatomic,strong) ColorPickerViewController *colorChooseVc;


@end

@implementation DiyDrawViewController
{
    DiyDrawView *drawView;
    unsigned char*sBytes;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    drawView = [[DiyDrawView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64)];
    drawView.delegate = self;
    [self.view addSubview:drawView];
    
    self.title = @"Diy 画板";
}

#pragma mark - DrawViewOptionDelegate
-(void)selectLineColor
{
    self.colorChooseVc.chooseColor = drawView.LineColor;
    
    [self.navigationController pushViewController:_colorChooseVc animated:YES];
}

-(void)saveImageAfterDone:(UIImage *)image// bytes:(unsigned char*)imageBytes
{
//    //1.保存到本地相册
//    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//        //写入图片到相册
//        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
//    } completionHandler:^(BOOL success, NSError * _Nullable error) {
//        
//        NSLog(@"success = %d, error = %@", success, error);
//        if (error) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [SVProgressHUD showImage:nil status:@"保存失败，请重试"];
//            });
//        }else {
//            dispatch_async(dispatch_get_main_queue(), ^{
//            [SVProgressHUD showImage:nil status:@"保存成功！"];
//            });
////            //2.调用蓝牙
////            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////                //注：不要忘记释放malloc的内存
////                BlueToothService * s = [BlueToothService sharedDefaultManager];
////                [s sendImageToBlueTooth:image perHeader:STATIC_HEAD_16];
////                free(sBytes);
////            });
//        }
//    }];
//    sBytes = imageBytes;
     [self addImageViewTolocal:image];
}

-(void)addImageViewTolocal:(UIImage * )saveImage{
    
    [self saveImageToPhotos:saveImage];
}

- (void)saveImageToPhotos:(UIImage*)savedImage
{
//    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    
    NSMutableDictionary *imageMetaData = [NSMutableDictionary dictionary];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setValue:@"123" forKey:(NSString *)kCGImagePropertyExifUserComment];
    [imageMetaData setObject:dictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    
    [library writeImageToSavedPhotosAlbum:savedImage.CGImage metadata:imageMetaData completionBlock:^(NSURL *assetURL, NSError *error) {
        
    }];
     


}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo

{
    
    NSString *msg = nil ;
    
    if(error != NULL || image == nil){
        
        msg = @"保存图片失败" ;
        
    }else{
        
        msg = @"保存图片成功" ;
        
    }
    
        //注：不要忘记释放malloc的内存
        free(sBytes);
    [SVProgressHUD showInfoWithStatus:msg];
}

#pragma mark - lazyloading
-(ColorPickerViewController *)colorChooseVc
{
    if (!_colorChooseVc) {
        _colorChooseVc = [[ColorPickerViewController alloc]init];
        [_colorChooseVc addObserver:self forKeyPath:@"chooseColor" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    }
    return _colorChooseVc;
}

#pragma mark - KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"chooseColor"]) {
        drawView.LineColor = self.colorChooseVc.chooseColor;
        drawView.cancleEraser = YES;
    }
}

-(void)dealloc
{
    [_colorChooseVc removeObserver:self forKeyPath:@"chooseColor"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
